package edu.hcmus.sow.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.encoding.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import edu.hcmus.sow.dao.UserDAO;
import edu.hcmus.sow.dao.UserProfileDAO;
import edu.hcmus.sow.domain.User;
import edu.hcmus.sow.domain.UserProfile;

@Service
@Transactional
public class UserService {

   @Autowired
   PasswordEncoder passwordEncoder;

   @Autowired
   private UserDAO userDAO;

   @Autowired
   private UserProfileDAO userProfileDAO;

   public void saveUser(User user) {
      if (user.getId() != null) {
         if (!user.getPassword().isEmpty())
            user.setPassword(passwordEncoder.encodePassword(user.getPassword(), null));
         user = userDAO.merge(user);
      } else {
         user.setPassword(passwordEncoder.encodePassword(user.getPassword(), null));
         user = userDAO.persist(user);
      }
   }

   public User getUserByID(Integer userID) {
      User user = userDAO.findById(userID);
      return user;
   }

   public UserProfile getUserProfileByUserID(Integer userID) {
      UserProfile up = userProfileDAO.getByUserID(userID);
      return up;
   }
}
